<template>
  <div class="sales-report-container">
   
    <!-- 顶部操作栏 -->
    <el-row :gutter="20" class="operation-bar">
      <el-col :span="8">
        <div> <h2 style="font-weight:700;">业务员销售列表</h2></div>
      </el-col>
     
      <el-col :span="5">
        <el-input
          v-model="searchQuery"
          placeholder="请输入业务员工姓名查询"
          suffix-icon="el-icon-search"
          @keyup.enter="handleSearch"
        />
      </el-col>
      <el-col :span="2">
        <el-button @click="handleSearch">搜索</el-button>
      </el-col>
    </el-row>

    <!-- 销售报表表格 -->
    <el-table
      :data="reportList"
      border
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column prop="businessmanId" label="ID" width="50" />
      <el-table-column prop="name" label="业务员" />
      <el-table-column prop="fenPeiTotal" label="分配设备数" />
      <el-table-column prop="chengJiaoTotal" label="成交订单数" />
      <el-table-column prop="dingDanTotal" label="订单金额" />
      <el-table-column label="成单率">
          <template #default="scope">
              {{ scope.row.chengDan !== null && scope.row.chengDan !== undefined ? scope.row.chengDan + '%' : '0%' }}
          </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click="handleBelongDevice(scope.row)">负责设备</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNo"
      :page-sizes="[2, 5, 10, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 归属设备模态框 -->
    <el-dialog
      title="业务员负责设备列表"
      v-model="deviceDialogVisible"
      width="900px"
      :before-close="handleDeviceDialogClose"
    >
     <div>当前业务员：{{ currentSalesman }}</div>

 <!-- 归属设备列表表格 -->
  <el-table
    :data="deviceList"
    border
    style="width: 100%"
    :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    :empty-text="isLoadingDevice ? '加载中...' : '该业务员暂无负责设备'"
  >

    <!-- 设备表格列（可根据实际接口返回的设备字段调整prop） -->
    <el-table-column prop="equipmentId" label="设备ID" width="80" align="center" />
    <el-table-column prop="brand" label="设备品牌" min-width="180" />
    <el-table-column prop="model" label="设备型号" min-width="150" />
    <el-table-column prop="year" label="设备年份" min-width="150" />
    <el-table-column prop="price" label="设备价格" min-width="150" />
    <el-table-column prop="contactName" label="设备联系人" min-width="150" />
    <el-table-column prop="contactPhone" label="设备联系电话" min-width="150" />
    <el-table-column prop="releaseTime" label="发布时间" min-width="180">
      <template #default="scope">
        {{ formatDate(scope.row.releaseTime) }}
      </template>
    </el-table-column>
    <el-table-column prop="status" label="设备状态" width="120">
      <template #default="scope">
        <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
          {{ scope.row.status === 0 ? '未审核':scope.row.status === 1 ? '已上架':scope.row.status === 2 ? '已下架':scope.row.status === 3 ? '已成交':'设备状态异常'}}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="location" label="设备所在地（省/ 市 / 区）" min-width="200" />
  </el-table>



      <template #footer>
        <el-button @click="handleDeviceDialogClose">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import httpInstance from '../../utils/http';
import { ElMessage } from 'element-plus';

// 报表数据
const reportList = ref([]);

// 搜索条件
const searchQuery = ref('');

// 分页参数
const pageNo = ref(1);       // 当前页码
const pageSize = ref(5);     // 每页条数
const total = ref(0);        // 总数据条数

// 归属设备模态框相关
const deviceDialogVisible = ref(false);
const currentSalesman = ref('');


// 2. 归属设备列表数据
const deviceList = ref([]);
// 3. 当前选中业务员的ID（用于请求其名下设备）
const currentSalesmanId = ref('');

onMounted(() => {
  getXiaoShouList();
});

// 获取业务员的销售报表
const getXiaoShouList = async () => { 
  try {
    const { data: res } = await httpInstance.post(
      `/eduservice/businessman/getXiaoShou/${pageNo.value}/${pageSize.value}`,
      { name: searchQuery.value }
    );
    reportList.value = res.data.list.list;
    total.value = res.data.list.total;
  } catch (error) {
    ElMessage.error('获取业务员的销售报表失败');
  }
};

// 分页事件：每页条数改变时触发
const handleSizeChange = (val) => {
  pageSize.value = val;  // 更新每页条数
  pageNo.value = 1;      // 重置为第一页
  getXiaoShouList();     // 重新加载数据
};

// 分页事件：当前页码改变时触发
const handleCurrentChange = (val) => {
  pageNo.value = val;    // 更新当前页码
  getXiaoShouList();     // 重新加载数据
};


// 1. 获取当前业务员的设备列表（核心接口请求）
const getSalesmanDeviceList = async () => {
  try {
    // 接口说明：传业务员ID，获取其负责的设备（请根据实际接口路径调整）
    const {data:res} = await httpInstance.post( `eduservice/businessman/getBusinessmanEquipmentByBusinessmanId/${currentSalesmanId.value}`);
    deviceList.value = res.data.list || [];
      console.log('设备数据:', deviceList);

  } catch (error) {
    console.error('获取设备列表失败：', error);
    ElMessage.error('获取设备信息失败，请重试');
    deviceList.value = [];
  } finally {
  }
};

// 获取业务员归属设备列表
const handleBelongDevice = (row) => {
  currentSalesman.value = row.name;  // 修正为row.name（匹配业务员姓名字段）
  currentSalesmanId.value = row.businessmanId; // 记录当前业务员ID
  deviceDialogVisible.value = true; // 打开模态框
  getSalesmanDeviceList(); // 立即请求该业务员的设备数据
  
};

// 3. 关闭设备模态框（重置数据，避免残留）
const handleDeviceDialogClose = () => {
  deviceDialogVisible.value = false;
  currentSalesmanId.value = '';
  deviceList.value = [];
};

// 搜索功能
const handleSearch = () => {
  pageNo.value = 1;      // 搜索时重置为第一页
  getXiaoShouList();
};

// 修改后：替换T为空格，保留年月日和时分秒
const formatDate = (dateStr) => {
  // 若日期为空或非字符串，返回空值避免报错
  if (!dateStr || typeof dateStr !== 'string') return '';
  // 将日期中的"T"替换为空格，保留完整的年月日和时分秒
  return dateStr.replace('T', ' ');
};
</script>

<style scoped>
.sales-report-container {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}
</style>